import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

import '../../http/user.dart';
import '../../i18n/locale_keys.dart';
import '../../models/request/user_register_req.dart';
import '../../utils/loading.dart';

class Register_pinLogic extends GetxController {
  // ping 文字输入控制器
  TextEditingController pinController = TextEditingController();
  // 表单 key
  GlobalKey formKey = GlobalKey<FormState>();

  // 注册界面传值
  UserRegisterReq? req = Get.arguments;

  // 这里默认一个 pin 值，生产环境在服务端验证
  String pinCheckValue = '111111';


  // 按钮返回
  void onBtnBackup() {
    Get.back();
  }

  @override
  void onClose() {
    super.onClose();
    pinController.dispose();
  }

  // 验证 pin
  String? pinValidator(val) {
    return val == pinCheckValue ? null : LocaleKeys.commonMessageIncorrect.trParams({"method": "Pin"});
  }


  // 注册
  Future<void> _register() async {
    try {
      Loading.show();
      // 检查 Pin
      if (pinController.text.isEmpty || pinController.text != pinCheckValue) {
        return Loading.error(
            LocaleKeys.commonMessageIncorrect.trParams({"method": "Pin"}));
      }

      // 注册提交
      bool isOk = await UserApi.register(req);
      if (isOk) {
        Loading.success(LocaleKeys.commonMessageSuccess.trParams({"method": "Register"}));
        Get.back(result: true);
      }

    } on DioException catch (e) {
      // 捕获 Dio 错误
      print('--- Dio 错误详情 ---');
      print('错误类型: ${e.type}');
      print('错误信息: ${e.message}');
      print('错误原因: ${e.error}');
      print('状态码: ${e.response?.statusCode}');
      print('响应数据: ${e.response?.data}');
      print('请求配置: ${e.requestOptions.uri}');
    } catch (e)  {
      print(e.toString());
    } finally{
      Loading.dismiss();
    }
  }

  // pin 触发提交
  void onPinSubmit(String val) {
    debugPrint("onPinSubmit: $val");
    _register();
  }

  // 按钮提交
  void onBtnSubmit() {
    _register();
  }

}
